const { Service } = require("egg");

class TopicLessonExamService extends Service {
  async create(data) {
    const { lessonId, userId, exams } = data;
    const examRecord = await this.app.model.TopicLessonExam.create({
      lessonId,
      userId,
      exams,
      answers: "",
    });
    return examRecord;
  }

  async id(id) {
    const examRecord = await this.app.model.TopicLessonExam.findByPk(id, {
      raw: true,
    });
    return examRecord;
  }
  async updateAnswers(data) {
    const { id, answers } = data;
    const [affectedRows] = await this.app.model.TopicLessonExam.update(
      { answers },
      { where: { id } }
    );
    if (affectedRows === 0) {
      return null;
    }
    return this.id(id);
  }

  async calcResult(list, answers) {
    let num = 0;

    let exams = []

    try {
      if (typeof list === "string") {
        exams = JSON.parse(list);
      }
    } catch {

    }

    exams.forEach((element, index) => {
      const { type, correctAnswers } = element;

      const answer = answers[index];

      if (type.trim() === "单选题") {
        if (answer === correctAnswers) {
          num++;
        }
      } else if (type.trim() === "多选题") {
        try {
          const correctAnswersStr = correctAnswers.sort().join("");

          if (answer === correctAnswersStr) {
            num++;
          }
        } catch (error) {}
      }
    });

    const percent = (num / exams.length) * 100;

    const isInteger = percent % 1 === 0; // 判断是否为整数
    const formattedPercent = isInteger
      ? percent
      : parseFloat(percent.toFixed(1));

    return {
      num,
      percent: formattedPercent,
    };
  }
}

module.exports = TopicLessonExamService;
